﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using D.ATN.Dto;
using D.ATN.Events;
using D.ATN.Extensions;
using D.ATN.HttpUtil;
using D.ATN.Models;
using D.ATN.NLogsUtil;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RTools_NTS.Util;

namespace D.ATN
{
    public partial class FrmAddJob : Form
    {
        public FrmAddJob()
        {
            InitializeComponent();

            this.cboLds.SelectedValueChanged += CboLds_SelectedValueChanged;
        }

        private async void FrmAddJob_Load(object sender, EventArgs e)
        {
            LoadUiData();
            await LoadEnvAsync();
            await LoadDcItemAsync();
        }

        private List<EnvSettingEntity> envSettingEntities = null;
        private async Task LoadEnvAsync()
        {
            envSettingEntities = await ServiceLocator.MySqllite.Select<EnvSettingEntity>().ToListAsync();
            this.cboEnv.DisplayMember = "Name";
            this.cboEnv.DataSource = envSettingEntities;
        }

        private List<SPCFabEntity> fabEntities = null;
        private async Task LoadFabAsync()
        {
            fabEntities = await ServiceLocator.SpcFreeSql.Select<SPCFabEntity>().ToListAsync();
            this.cboFab.DisplayMember = "fab_id";
            this.cboFab.DataSource = fabEntities;
        }

        private async void CboLds_SelectedValueChanged(object sender, EventArgs e)
        {
            if (cboLds.SelectedItem != null)
            {
                await LoadAreaAsync(cboLds.SelectedItem.ToString());
            }
        }

        private List<SPCDeparmentEntity> sPCDeparmentEntities = null;
        private async Task LoadAreaAsync(string area_type)
        {
            sPCDeparmentEntities = await ServiceLocator.SpcFreeSql.Select<SPCDeparmentEntity>().Where(m => m.area_type == area_type).ToListAsync();
            this.cboDeparment.DisplayMember = "area_id";
            this.cboDeparment.DataSource = sPCDeparmentEntities;
        }

        private async Task LoadDcItemAsync()
        {
            txtKeyDcItem.Text = "";
            checkMESDcitem.Items.Clear();

            //var dcItemList = await ServiceLocator.MesFreeSql.Select<MESDcItemEntity>().Distinct().ToListAsync();
            //var array = dcItemList.Select(m => m.DCITEM_NAME).ToArray();
            checkMESDcitem.Items.AddRange(ServiceLocator.DcItemList.ToArray());
        }

        private async void LoadUiData()
        {
            this.cboEdcLevel.Items.Clear();
            this.cboEdcLevel.Items.Add("SITE");
            this.cboEdcLevel.Items.Add("WAFER");
            this.cboEdcLevel.Items.Add("LOT");
            this.cboEdcLevel.Items.Add("BATCH");
            this.cboEdcLevel.Text = "WAFER";

            cboLds.Items.Clear();
            cboLds.Items.Add("RT");
            cboLds.Items.Add("NonRT");
            cboLds.Items.Add("NonLot");

            this.checkKeyChart.Checked = true;

            this.txtUSLForXbar.Text = "1000";
            this.txtTargetForXbar.Text = "500";
            this.txtLSLForXbar.Text = "100";
            this.txtUCLForXbar.Text = "800";
            this.txtCLForXbar.Text = "500";
            this.txtLCLForXbar.Text = "300";

            this.txtUSLForTREND.Text = "1000";
            this.txtTargetForTREND.Text = "500";
            this.txtLSLForTREND.Text = "100";
            this.txtUCLForTREND.Text = "800";
            this.txtCLForTREND.Text = "500";
            this.txtLCLForTREND.Text = "300";

            this.txtUSLForR.Text = "1000";
            this.txtTargetForR.Text = "500";
            this.txtLSLForR.Text = "-100";
            this.txtUCLForR.Text = "800";
            this.txtCLForR.Text = "500";
            this.txtLCLForR.Text = "-50";

            this.txtUSLForS.Text = "1000";
            this.txtTargetForS.Text = "500";
            this.txtLSLForS.Text = "-100";
            this.txtUCLForS.Text = "800";
            this.txtCLForS.Text = "500";
            this.txtLCLForS.Text = "-50";

            this.txtTotalChartCount.Value = 10;
        }

        /// <summary>
        /// 创建job
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnBatchCreate_Click(object sender, EventArgs e)
        {
            #region 数据校验

            var envSettingEntity = this.cboEnv.SelectedItem as EnvSettingEntity;
            if (string.IsNullOrEmpty(cboFab.Text.Trim()))
            {
                MessageBox.Show("请填写Chart名称！"); return;
            }

            if (string.IsNullOrEmpty(txtChartName.Text.Trim()))
            {
                MessageBox.Show("请填写Chart名称！"); return;
            }
            if (string.IsNullOrEmpty(cboEdcLevel.Text.Trim()))
            {
                MessageBox.Show("请选择监控级别！"); return;
            }
            var fabEntity = this.cboFab.SelectedItem as SPCFabEntity;
            if (fabEntity == null)
            {
                MessageBox.Show("请选择车间/工厂！"); return;
            }
            if (cboLds.SelectedItem == null)
            {
                MessageBox.Show("请选择LDS！"); return;
            }

            //if (treeSubFolder.SelectedNode == null)
            //{
            //    MessageBox.Show("请选择Folder！"); return;
            //}

            if (cboDeparment.SelectedItem == null)
            {
                MessageBox.Show("请选择部门！"); return;
            }

            #endregion

            var dcItems = new List<string>();
            if (checkAllDcItem.Checked)
            {
                foreach (var item in checkMESDcitem.Items)
                {
                    dcItems.Add(item.ToString());
                }
            }
            else
            {
                dcItems.Add(txtKeyDcItem.Text);
            }

            var index = 0;
            List<SPCAddJobRequestDto> jobRequestDtos = new List<SPCAddJobRequestDto>();
            var totalCount = (int)txtTotalChartCount.Value;

            for (int i = 0; i < totalCount; i++)
            {
                foreach (var dcItem in dcItems)
                {
                    #region 组装数据

                    Step1 step1 = new Step1()
                    {
                        JobID = "New",
                        JobName = $"{txtChartName.Text.Trim()}-{dcItem}-{index}",
                        JobVersion = 1,
                        DataType = "Variable",
                        JobStatus = "Active",
                    };
                    step1.Fab = cboFab.SelectedText;
                    step1.Area = "ALL";
                    step1.ControlStatus = "SPC Control";
                    step1.EffectiveData = DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss.ffff");
                    step1.OCAPType = txtOCAPTemplateID.Text;
                    step1.M1OPNo = "AARON_STEP_D1";
                    step1.M1OPNoSeq = "019100";
                    step1.KeyChartFlag = checkKeyChart.Checked ? "KEY(Y)" : "";
                    step1.EDCLevel = cboEdcLevel.SelectedText;

                    #region 空

                    step1.MailCount = 25;
                    step1.Mail = new List<string>();
                    step1.Department = "";
                    step1.EquipmentDepartment = "";
                    step1.Tag = "";
                    step1.Cparea = "";
                    step1.MEAS_Des = "";
                    step1.SpecialJob = false;
                    step1.ProductApplication = "";
                    step1.LotType = new List<string>();
                    step1.ProdList3 = new List<string>();
                    step1.ProdList2 = new List<string>();
                    step1.Customer = new List<string>();
                    step1.M1RouteSeq = "";
                    step1.M1Route = "";
                    step1.M1Recipe = "*";
                    step1.M1EQP = "*";
                    step1.P1RouteSeq = "";
                    step1.P1Route = "";
                    step1.P1OPNo = "";
                    step1.P1OPNoSeq = "";
                    step1.P1Recipe = "";
                    step1.P1EQP = "";
                    step1.M2RouteSeq = "";
                    step1.M2Route = "";
                    step1.M2OPNo = "";
                    step1.M2OPNoSeq = "";
                    step1.M2Recipe = "";
                    step1.M2EQP = "";
                    step1.P2RouteSeq = "";
                    step1.P2Route = "";
                    step1.P2OPNo = "";
                    step1.P2OPNoSeq = "";
                    step1.P2Recipe = "";
                    step1.P2EQP = "";
                    step1.P3RouteSeq = "";
                    step1.P3Route = "";
                    step1.P3OPNo = "";
                    step1.P3OPNoSeq = "";
                    step1.P3Recipe = "";
                    step1.P3EQP = "";
                    step1.KeyChartFlagSelect = new List<string>();
                    step1.RadioNonRTKey = "";
                    step1.NonRTKeyChart = new List<string>();
                    step1.Formual = "";
                    step1.Time = "";
                    step1.DeriveChartName = "";
                    step1.ProdList = "";
                    step1.EMASInterval = "";
                    step1.Reciplist = new List<string>();
                    step1.WarningTime = "";
                    step1.MailType = new List<string>() { "Alarm" };
                    step1.EmailTemplate = "Default";
                    step1.TemplateName = "Custom Template";
                    step1.Showcolumn = "";
                    step1.MailInfo = "";
                    step1.ToMailListType = "Mail";
                    step1.CCMailListType = "Mail";
                    step1.ToinputMail = "";
                    step1.CCinputMail = "";
                    step1.MailGroup = "";
                    step1.CCMailGroup = "";
                    step1.ToMailEnd = "";
                    step1.CCMailEnd = "";
                    step1.MailListDataSource = new List<string>();
                    step1.CCMailListDataSource = new List<string>();
                    step1.MailListTable = new MailListTable() { currentSelectRow = new List<string>(), currentSelectRowKey = new List<string>() };
                    step1.CCMailListTable = new CCMailListTable() { currentSelectRow = new List<string>(), currentSelectRowKey = new List<string>() };
                    #endregion

                    if (cboLds.SelectedText != null)
                    {
                        step1.JobType = cboLds.SelectedText.ToString().ToUpper() == "INLINE" ? "RT" : "NoneRT";
                    }

                    Step2 step2 = new Step2();
                    step2.ControlItem = dcItem;
                    step2.ControlItemStep = new List<string>() { "Step1" };
                    step2.ControlItemStepSelect = "Step1";
                    step2.ControlItemDataSource = new List<ControlItemDataSourceItem>()
                {
                     new ControlItemDataSourceItem()
                     {
                        value= "V1",
                        operation= "Step1",
                        dcitem= dcItem,
                        wafer= "*",
                        site= "*",
                     }
                };
                    step2.ControlItemTable = new ControlItemTable() { currentSelectRow = new List<string>(), currentSelectRowKey = new List<string>() };
                    step2.VarDCItemList = new List<VarDCItemListItem>()
                {
                    new VarDCItemListItem() {
                        Value= "V1",
                        Operation= "M1",
                        DCItem= dcItem,
                        Wafer= "*",
                        Site= "*"
                    }
                };
                    step2.ControlItemList = "{V1=@M1:" + dcItem + ":w*:s*}{V1}";
                    step2.ControlItemListRel = "V1";
                    step2.ControlItemValue = "V1";
                    step2.XbarType = "XBAR";
                    step2.Defect = "BAD";
                    step2.Sample = "TOTAL";
                    step2.VariableCheckbox = new List<string>() { "BLOT", "Range", "S" };
                    step2.AttributeCheckbox = "P";
                    step2.MovingChartCheckBox = new List<string>();
                    step2.MMFactor = 7;
                    step2.MAFactor = 7;
                    step2.MSFactor = 2;
                    step2.EWMAMFactor = 0.4;
                    step2.EWMASFactor = 0.4;
                    step2.EWMARFactor = 0.4;
                    step2.Wafer = "*";
                    step2.Site = "*";
                    step2.ControlItemModel = new ControlItemModel()
                    {
                        visible = false,
                        isCreate = true,
                        status = new Status() { loading = false }
                    };
                    step2.ControlItemValue = "V1";


                    #region step3
                    Step3 step3 = new Step3();
                    step3.XbarSpecType = "Manual";
                    step3.XbarControlType = "Manual";
                    step3.XbarWarnSigma = "";
                    step3.XbarUsl = 1000;
                    step3.XbarTarget = 500;
                    step3.XbarLsl = 100;
                    step3.XbarUcl = 800;
                    step3.XbarCl = 500;
                    step3.XbarLcl = 300;
                    step3.XSpecType = "Manual";
                    step3.XControlType = "Manual";
                    step3.XWarnSigma = "";
                    step3.XUsl = "";
                    step3.XTarget = "";
                    step3.XLsl = "";
                    step3.XUcl = "";
                    step3.XCl = "";
                    step3.XLcl = "";
                    step3.BlotSpecType = "Manual";
                    step3.BlotControlType = "Manual";
                    step3.BlotUsl = 1000;
                    step3.BlotTarget = 500;
                    step3.BlotLsl = 100;
                    step3.BlotUcl = 800;
                    step3.BlotCl = 500;
                    step3.BlotLcl = 300;
                    step3.SSpecType = "Manual";
                    step3.SControlType = "Manual";
                    step3.SWarnSigma = "";
                    step3.SUsl = 100;
                    step3.STarget = 50;
                    step3.SLsl = 10;
                    step3.SUcl = 80;
                    step3.SCl = 50;
                    step3.SLcl = 30;
                    step3.RSpecType = "Manual";
                    step3.RControlType = "Manual";
                    step3.RWarnSigma = "";
                    step3.RUsl = 100;
                    step3.RTarget = 50;
                    step3.RLsl = 10;
                    step3.RUcl = 80;
                    step3.RCl = 50;
                    step3.RLcl = 30;
                    step3.MRSpecType = "Manual";
                    step3.MRControlType = "Manual";
                    step3.MRWarnSigma = "";
                    step3.MRUsl = "";
                    step3.MRTarget = "";
                    step3.MRLsl = "";
                    step3.MRUcl = "";
                    step3.MRCl = "";
                    step3.MRLcl = "";
                    step3.PSpecType = "Manual";
                    step3.PControlType = "Manual";
                    step3.PWarnSigma = "";
                    step3.PUsl = "";
                    step3.PTarget = "";
                    step3.PLsl = "";
                    step3.PUcl = "";
                    step3.Pcl = "";
                    step3.PLcl = "";
                    step3.NPSpecType = "Manual";
                    step3.NPControlType = "Manual";
                    step3.NPWarnSigma = "";
                    step3.NPUsl = "";
                    step3.NPTarget = "";
                    step3.NPLsl = "";
                    step3.NPUcl = "";
                    step3.NPcl = "";
                    step3.NPLcl = "";
                    step3.CSpecType = "Manual";
                    step3.CControlType = "Manual";
                    step3.CWarnSigma = "";
                    step3.CUsl = "";
                    step3.CTarget = "";
                    step3.CLsl = "";
                    step3.CUcl = "";
                    step3.Ccl = "";
                    step3.CLcl = "";
                    step3.USpecType = "Manual";
                    step3.UControlType = "Manual";
                    step3.UWarnSigma = "";
                    step3.UUsl = "";
                    step3.UTarget = "";
                    step3.ULsl = "";
                    step3.UUcl = "";
                    step3.Ucl = "";
                    step3.ULcl = "";
                    step3.EWMAMSpecType = "Manual";
                    step3.EWMAMControlType = "Manual";
                    step3.EWMAMWarnSigma = "";
                    step3.EWMAMUsl = "";
                    step3.EWMAMTarget = "";
                    step3.EWMAMLsl = "";
                    step3.EWMAMUcl = "";
                    step3.EWMAMCl = "";
                    step3.EWMAMLcl = "";
                    step3.EWMASSpecType = "Manual";
                    step3.EWMASControlType = "Manual";
                    step3.EWMASWarnSigma = "";
                    step3.EWMASUsl = "";
                    step3.EWMASTarget = "";
                    step3.EWMASLsl = "";
                    step3.EWMASUcl = "";
                    step3.EWMASCl = "";
                    step3.EWMASLcl = "";
                    step3.EWMARSpecType = "Manual";
                    step3.EWMARControlType = "Manual";
                    step3.EWMARWarnSigma = "";
                    step3.EWMARUsl = "";
                    step3.EWMARTarget = "";
                    step3.EWMARLsl = "";
                    step3.EWMARUcl = "";
                    step3.EWMARCl = "";
                    step3.EWMARLcl = "";
                    step3.MMSpecType = "Manual";
                    step3.MMControlType = "Manual";
                    step3.MMWarnSigma = "";
                    step3.MMUsl = "";
                    step3.MMTarget = "";
                    step3.MMLsl = "";
                    step3.MMUcl = "";
                    step3.MMCl = "";
                    step3.MMLcl = "";
                    step3.MASpecType = "Manual";
                    step3.MAControlType = "Manual";
                    step3.MAWarnSigma = "";
                    step3.MAUsl = "";
                    step3.MATarget = "";
                    step3.MALsl = "";
                    step3.MAUcl = "";
                    step3.MACl = "";
                    step3.MALcl = "";
                    step3.MSSpecType = "Manual";
                    step3.MSControlType = "Manual";
                    step3.MSWarnSigma = "";
                    step3.MSUsl = "";
                    step3.MSTarget = "";
                    step3.MSLsl = "";
                    step3.MSUcl = "";
                    step3.MSCl = "";
                    step3.MSLcl = "";
                    step3.D1SpecType = "Manual";
                    step3.D1ControlType = "Manual";
                    step3.D1WarnSigma = "";
                    step3.D1Usl = "";
                    step3.D1Target = "";
                    step3.D1Lsl = "";
                    step3.D1Ucl = "";
                    step3.D1Cl = "";
                    step3.D1Lcl = "";
                    step3.OutlineShow = true;
                    step3.Step1OperationShow = true;
                    step3.Step1OperationUpper = 9999999;
                    step3.Step1OperationLower = -9999999;
                    step3.Step2OperationShow = false;
                    step3.Step2OperationUpper = 999999;
                    step3.Step2OperationLower = -999999;
                    step3.Step3OperationShow = false;
                    step3.Step3OperationUpper = 999999;
                    step3.Step3OperationLower = -999999;
                    step3.Step4OperationShow = false;
                    step3.Step4OperationUpper = 999999;
                    step3.Step4OperationLower = -999999;
                    step3.Step5OperationShow = false;
                    step3.Step5OperationUpper = 999999;
                    step3.Step5OperationLower = -999999;
                    step3.BLOTShow = true;
                    step3.SShow = true;
                    step3.Rshow = true;
                    step3.MRShow = false;
                    step3.EWMAMShow = false;
                    step3.EWMASShow = false;
                    step3.EWMARShow = false;
                    step3.MMShow = false;
                    step3.MAShow = false;
                    step3.MSShow = false;
                    step3.D1 = false;
                    step3.OCAPHold = "Y";
                    step3.EqipHold = "Y";
                    step3.EquipList = new List<string>();
                    step3.D1Show = false;
                    #endregion

                    #region step4
                    Step4 step4 = new Step4();
                    step4.EquipList = new List<string>() { "Equip Hold" };
                    step4.ShowSelectValue = new List<ShowSelectValueItem>() {
                    new ShowSelectValueItem()
    {
        key = "XBAR",
                        SelectRule = new List<string>() { "WE1" }
                    },
                    new ShowSelectValueItem()
    {
        key = "BLOT",
                        SelectRule = new List<string>() { "RawDataOOC", "RawDataOOS" }
                    },
                    new ShowSelectValueItem()
    {
        key = "R",
                        SelectRule = new List<string>() { "WE1" }
                    },
                    new ShowSelectValueItem()
    {
        key = "S",
                        SelectRule = new List<string>() { "WE1" }
                    }
};


                    step4.TableSelectValue = new List<TableSelectValueItem>()
                {
                    new TableSelectValueItem()
                    {
                        key= "RawDataOOC",
                        title= "RawDataOOC: 超出RawData上下管制界限",
                        showlist= new List<ShowlistItem>() {
                            new ShowlistItem() { key= "XBAR",select= false},
                            new ShowlistItem() { key= "BLOT",select= false},
                            new ShowlistItem() { key= "R",select= false},
                            new ShowlistItem() { key= "S",select= false}
                            }
                    },
                    new TableSelectValueItem()
                    {
                        key= "RawDataOOC",
                        title= "RawDataOOC: 超出RawData上下管制界限",
                        showlist= new List<ShowlistItem>() {
                            new ShowlistItem() { key= "XBAR",select= false},
                            new ShowlistItem() { key= "BLOT",select= true},
                            new ShowlistItem() { key= "R",select= false},
                            new ShowlistItem() { key= "S",select= false}
                        }
                    },
                    new TableSelectValueItem()
                    {
                        key= "WE1",
                        title= "WE1: 超出管制线",
                        showlist= new List<ShowlistItem>() {
                            new ShowlistItem() { key= "XBAR",select= true},
                            new ShowlistItem() { key= "BLOT",select= false},
                            new ShowlistItem() { key= "R",select= true},
                            new ShowlistItem() { key= "S",select= true}
                        }
                    },
                };

                    step4.RowDataRule = new List<string>() { "rawdataooc", "rawdataoos" };
                    #endregion


                    #endregion

                    SPCAddJobRequestDto sPCAddJobRequestDto = new SPCAddJobRequestDto()
                    {
                        Type = "New",
                        jobTreeID = 26,
                        Step1 = JsonConvert.SerializeObject(step1),
                        Step2 = JsonConvert.SerializeObject(step2),
                        Step3 = JsonConvert.SerializeObject(step3),
                        Step4 = JsonConvert.SerializeObject(step4),
                    };
                    jobRequestDtos.Add(sPCAddJobRequestDto);
                }
            }


            var successCount = 0;
            var failCount = 0;
            var url = $"http://{envSettingEntity.WebAPIIP}:{envSettingEntity.WebAPIPort}/{ServiceLocator.SPC_CREATE_RT_JOB_URL}";

            var token = txtToken.Text.Trim();
            if (string.IsNullOrEmpty(txtToken.Text))
            {
                token = await GetToken(envSettingEntity.WebAPIIP, envSettingEntity.WebAPIPort);
                if (token == null)
                {
                    MessageBox.Show("获取Token失败");
                    return;
                }
            }

            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("Authorization", "Bearer "+token);

            foreach (SPCAddJobRequestDto item in jobRequestDtos)
            {
                var res = await HttpClientHelper.HttpPostAsync<JobAddResponseDto>(url, ServiceLocator.TimeOut, item, "application/json", header);
                if (res.code == 999)
                {
                    successCount += 1;
                    UtilEvents.Defaut.GetEvent<AddChartEvent>().Publish(new AddChartEventArgs(index, item, totalCount, successCount, failCount));
                }
                else
                {
                    failCount += 1;
                    UtilEvents.Defaut.GetEvent<AddChartEvent>().Publish(new AddChartEventArgs(index, item, totalCount, successCount, failCount, false, res.message));
                }
            }
        }

        private async Task<string> GetToken(string ip, string port)
        {
            var url = $"http://{ip}:{port}/{ServiceLocator.SPC_LOGIN_URL}";

            //MD5 md5 = MD5.Create();
            //byte[] b = Encoding.UTF8.GetBytes("123456");
            //byte[] md5b = md5.ComputeHash(b);
            //md5.Clear();
            //StringBuilder sb = new StringBuilder();
            //foreach (byte item in md5b)
            //{
            //    sb.Append(item.ToString("x2"));
            //}

            var loginDto = new SPCLoginRequestDto()
            {
                userName = "SPC",
                password = "123",
                fabID = "",
            };

            var res = await HttpClientHelper.HttpPostAsync<LoginResultDto>(url, ServiceLocator.TimeOut, loginDto);
            if (res.code == 1 && res.response != null)
            {
                return res.response.AccessToken;
            }
            return null;
        }

        private void btnShowResult_Click(object sender, EventArgs e)
        {
            //var frmAddChartResult = new FrmAddChartResult();
            //frmAddChartResult.ShowDialog();
        }

        private void cboEnv_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.btnConn.Enabled = true;
        }

        private async void btnConn_Click(object sender, EventArgs e)
        {
            try
            {
                var envSettingEntity = this.cboEnv.SelectedItem as EnvSettingEntity;
                if (envSettingEntity != null)
                {
                    var initRes = await ResetFreeSql(envSettingEntity);
                    if (initRes == 0)
                    {// 成功、重新加载所有数据 
                        LoadUiData();
                        this.btnConn.Enabled = false;

                        await LoadFabAsync();
                    }
                    else if (initRes == 1)
                    {// spc连接失败
                        MessageBox.Show("SPC数据库连接异常");
                    }
                    else if (initRes == 2)
                    {// mes连接失败
                        MessageBox.Show("MES数据库连接异常");
                    }
                    else
                    {// -1 异常
                        MessageBox.Show("数据库连接异常");
                    }
                }
                else
                {
                    MessageBox.Show("请选择数据库链接");
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex.Message);
                MessageBox.Show("数据库连接异常");
            }
        }

        public async Task<int> ResetFreeSql(EnvSettingEntity env)
        {
            // 拼接连接字符串(service Name 不行)
            var spcConnStr = string.Empty;
            var mesConnStr = string.Empty;

            if (!string.IsNullOrEmpty(env.SPCIp))
            {
                //spcConnStr = $"Host={env.SPCIp};Port={env.SPCPort};Username={env.SPCAccount};Password={env.SPCPwd}; Database={env.SPCDataBase};ArrayNullabilityMode=Always;Pooling=true;Minimum Pool Size=1";
                spcConnStr = $"Host={env.SPCIp}:{env.SPCPort};database={env.SPCDataBase};user id={env.SPCAccount};password={env.SPCPwd};searchpath={env.SPCSearchPath};Maximum Pool Size=500;";
            }

            if (!string.IsNullOrEmpty(env.MESIp))
            {
                //mesConnStr = $"Host={env.MESIp};Port={env.MESPort};Username={env.MESAccount};Password={env.MESPwd}; Database={env.MESDataBase};ArrayNullabilityMode=Always;Pooling=true;Minimum Pool Size=1";
                mesConnStr = $"Host={env.MESIp}:{env.MESPort};database={env.MESDataBase};user id={env.MESAccount};password={env.MESPwd};searchpath={env.MESSearchPath};Maximum Pool Size=500;";
            }

            // 初始化DB
            return await OrmFactory.AddFreeSql(env.Name, mesConnStr, spcConnStr);
        }

        private void checkMESDcitem_SelectedIndexChanged(object sender, EventArgs e)
        {
            lblDcitemCount.Text = $"总监控数量：{checkMESDcitem.CheckedItems.Count}个";
        }
    }
}
